class Product {
    constructor() {
        this.detail = document.querySelector('.detail-con')

        //渲染
        this.init()
    }

    async init() {
        let id = this.getID(location.search)
        //得到分类后发送请求，获取该id的商品信息
        let data = await axios.get(`http://localhost:1998/all-goods/${id}`)
        data = data.data
        // //渲染页面
        this.createPage(data)
        
        //加减按钮
        this.subadd(data.price)

        //加入购物车
        this.addCart(data)

        //立即购买
        // this.buy(data)
    }
    //获取浏览器地址栏内的参数  ,获取分类
    getID(data) {
        var data = data.substr(1).split('&'); //把字符串分割为数组
        for (var i = 0; i < data.length; i++) {
            // search=%E9%9E%8B  =前面参数名 以=分割 如果等号前面的和参数名一样 返回=号后面的参数的值
            if (data[i].split('=')[0] == "id") {
                // 返回当前参数的值 同时转码
                return decodeURI(data[i].split('=')[1]);
            }
        }
    }

    //渲染页面
    createPage(data) {
        // console.log(data)
        let str = `
        

        <div class="leftbox">
            <div class="bigimg">
                <img src="${data.img.detailimg1}" alt="" class="zoom-image">
                <div class="bimg">
                  <img src="${data.img.bigimg1}" alt="" class="zoom-image" width="1200px" height="1200px">
                </div>
            </div>
            <div class="smallimg">
                <ul class="smalllist" id="smalllist">
                </ul>
            </div>
           
        </div>
        <div class="rightbox">
            <h1>${data.title}</h1>
            <div class="price">
                <h2>
                    <span style="font-size:20px">价格:</span>
                    <span style="font-size:24px">￥${data.price}&nbsp;&nbsp;&nbsp;</span>
                </h2>
            </div>
            
           
            <div class="number">
                <div class="num_left">
                    <span id="sp"></span>
                </div>
                <div>
                    <input class="num_mid" type="text" value="1">
                </div>
                <div class="num_right">
                    <span></span>
                </div>
            </div>
            <div class="anniu">
                <a href="#none">立即购买</a>
                <a href="javascript:void(0);" class="addBtn" >加入购物车</a>
            </div>
        </div>`
        this.detail.innerHTML = str
        //添加右边的放大镜，以及图片列表切换
        this.sw(data.img, data.id)

        //放大镜
        this.enlarge()

    }

    //图片列表切换
    sw(img) {
        //   console.log(img);
        //渲染小图标列表

        //获取小图标
        let str = ''
        for (let key in img) {
            //    console.log(key)
            let reg = /^(detailminimg)/
            let res = reg.test(key)
            //    console.log(res)
            if (res == true) {
                let num = key.slice(-1),
                    detailsrc = 'detailimg' + num,
                    detailbigsrc = 'bigimg' + num
                // console.log(num)
                str += `     <li>
                <a href="#none" data-image="${key}" data-zoom-image="${key}" onclick="clickIt('${key}','${img[detailsrc]}','${img[detailbigsrc]}')">
                    <img src="${img[key]}" alt="">
                </a>
               </li>`
            }
        }
        let img_ul = document.querySelector('#smalllist')
        img_ul.innerHTML = str
        //    console.log(img_min)
        //点击事件
    }

    //放大镜
    enlarge() {
        //鼠标进入
        let dbox = document.querySelector('.bigimg') //显示图片窗口
        let bbox = document.querySelector('.bimg')  //放大镜窗口
        let bigimg = document.querySelector('.bimg img') //放大镜图片
        //显示图片窗口宽高
        let sw = dbox.offsetWidth, sh = dbox.offsetHeight
        // console.log(sw, sh)

        //放大镜窗口宽高
        let bw = bbox.clientWidth, bh = bbox.clientHeight
        // console.log(bigimg.width, bh)

        // 获取放大镜缩放比例
        //宽
        let scaleW = bw / bigimg.width, scaleH = bh / bigimg.height
        // console.log(scaleW, scaleH)

        //创建小方块
        let s = document.createElement('div')
        s.className = 'moveOne'

        s.style.width = sw * scaleW + 'px'
        s.style.height = sh * scaleH + 'px'
        s.style.backgroundColor = "white"
        s.style.opacity = 0.3
        s.style.border = "1px solid black"
        s.style.position = "absolute"
        s.style.left=0
        s.style.top=0
        s.style.display="none"

        dbox.appendChild(s)


        //鼠标进入
        dbox.onmouseover = function () {
            s.style.display="block"
            bbox.style.visibility="visible"
            // console.log(dbox.offsetLeft,dbox.offsetTop)
            dbox.onmousemove=function(e){
                // 获取鼠标相对于盒子的距离
                let cx=e.pageX,cy=e.pageY
               
                 //限制移动范围，并使
                if(cx<=s.offsetWidth/2 + dbox.offsetLeft){
                    s.style.left=0+'px'
                }else if(cx>=dbox.offsetLeft+dbox.offsetWidth-s.offsetWidth/2){
                    s.style.left=dbox.offsetWidth-s.offsetWidth+'px'
                }
                else{
                    s.style.left=(cx-s.offsetWidth/2-dbox.offsetLeft) +'px'
                }
               
                if(cy<=s.offsetHeight/2 + dbox.offsetTop){
                    s.style.top=0+'px'
                }else if(cy>=dbox.offsetTop+dbox.offsetHeight-s.offsetHeight/2){
                    s.style.top=dbox.offsetHeight-s.offsetHeight+'px'
                }
                else{
                    s.style.top=(cy-s.offsetHeight/2-dbox.offsetTop) + 'px'
                }

                //获取移动比例
               let  scaleL=s.offsetLeft/dbox.offsetWidth,
                    scaleT=s.offsetTop/dbox.offsetHeight
                    
                bigimg.style.left=-(bigimg.offsetWidth*scaleL)+'px'
                bigimg.style.top=-(bigimg.offsetHeight*scaleT)+'px'
                
                
            }
        }
        
        dbox.onmouseleave=function (e){
            s.style.display="none"
            bbox.style.visibility="hidden"
        }

    }

    //加减按钮功能
    subadd(price){
        let sub=document.querySelector('#sp')
        ,add=document.querySelector('.num_right span'),
        pricele=document.querySelector('.price h2 span:nth-child(2)'),
        num=document.querySelector('.num_mid')

        // console.log(pricele)
        sub.onclick=function(){
             if(num.value>1){
                 num.value--
                 changePrice()
             }
        } 
        add.onclick=function(){
            num.value++
            changePrice()
        }

        function changePrice(){
            pricele.innerText='￥'+num.value*price
        }
    }

    //加入购物车
    addCart(data){
        let btn=document.querySelector('.addBtn')
        btn.onclick=async ()=>{
            if(!cookie){
                location.href='http://localhost:4023/html/login.html'
            }
            // console.log(data.id);
            //先看一下购物车你有没有
            let res=await axios.get(`http://localhost:1998/userinfo/${cookie}`)
            let carts=Array.from(res.data.carts)
            //看购物车中有没有该商品
            let has=carts.some(item=>{
                return item.id===data.id
            })
            // console.log(has);
            //获取该商品数量
            let num=document.querySelector('.num_mid')
            num=num.value-0
            // console.log(num);
            if(!has){
                //没有该商品了
                // console.log(carts);
                data.num=num
                data.checked=true
                carts.push(data)
                // console.log(carts);
            }else{
                //有该商品了
                carts.map(item=>{
                    item.id===data.id?item.num+=num:item.num
                })
            }
            res.data.carts=carts
            await axios.put(`http://localhost:1998/userinfo/${cookie}`,res.data)
            //加入成功
            let tip=document.querySelector('.loading')
            tip.style.opacity=1
            // clearInterval(timer)
            let timer=setInterval(() => {
                if(tip.style.opacity==0){
                    clearInterval(timer)
                }else{
                    tip.style.opacity-=0.02
                }  
            }, 50);
        }
    }

    //立即购买按钮
    // buy(data){
    //     console.log(data);
    //     let tbody=document.querySelector('.buy tbody')
    //     let num  = document.querySelector('.num_mid').value
    //     tbody.innerHTML=`<tr>
    //     <td>${data.name}</td>
    //     <td>${data.price}</td>
    //     <td>${num}</td>
    //    </tr>`
    //    let total=document.querySelector('.buy p')
    //    total.innerText=`共计：￥${data.price*num}`

    //    let btn=document.querySelector('.buy button')
    //    btn.onclick=()=>{}
       
    // }
   
}

new Product()

//图片切换
function clickIt(name, img, bigimg) {
    //   console.log(name,img,bigimg)
    let dimg = document.querySelector('.bigimg img')
    let bimg = document.querySelector('.bimg img')

    dimg.src = img
    bimg.src = bigimg

}